﻿using LiteDB;
using NordPixel.WPF.UnitOfWork.LiteDb.Support;
using System.Linq.Expressions;

namespace NordPixel.WPF.UnitOfWork.LiteDb.Core;

public class Repository<T> where T : class, new()
{
    private readonly LiteDBContext _dbContext;
    public readonly ILiteCollection<T> _collection;

    public Repository( LiteDBContext dbContext )
    {
        _dbContext = dbContext;
        _collection = _dbContext.Database.GetCollection<T>( NameDb<T>.NameInDb<T>() );
    }

    public T GetById( int id )
    {
        return _collection.FindById( id );
    }

    public IEnumerable<T> GetAll()
    {
        return _collection.FindAll();
    }

    public IEnumerable<T> Find( Expression<Func<T, bool>> predicate )
    {
        return _collection.Find( predicate );
    }

    public Guid Insert( T entity )
    {
        Guid id = _collection.Insert( entity );
        return id;
    }

    public void InsertBulk( IEnumerable<T> entities )
    {
        _collection.InsertBulk( entities );
    }

    public bool Update( T entity )
    {
        return _collection.Update( entity );
    }

    public void UpdateRange( IEnumerable<T> entities )
    {
        foreach (var entity in entities)
        {
            _collection.Update( entity );
        }
    }

    public bool Delete( Guid id )
    {
        return _collection.Delete( id );
    }

    public int Delete( Expression<Func<T, bool>> predicate )
    {
        return _collection.DeleteMany( predicate );
    }

    public int DeleteAll()
    {
        return _collection.DeleteMany( _ => true );
    }

    public long Count()
    {
        return _collection.Count();
    }

    public long Count( Expression<Func<T, bool>> predicate )
    {
        return _collection.Count( predicate );
    }

    public bool Exists( Expression<Func<T, bool>> predicate )
    {
        return _collection.Exists( predicate );
    }
}
